//
//  LXAlertView.m
//  ProjectSource_Demo
//
//  Created by Liu on 15/11/24.
//  Copyright © 2015年 AngryBear. All rights reserved.
//

#import "LXAlertView.h"

@interface LXAlertView ()
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIView *firstLine;

@property (nonatomic, strong) UIColor *blueColor;
@property (nonatomic, copy) void (^dismissBlock)(NSInteger cancelIndex, NSInteger clickIndex);


@end

@implementation LXAlertView

+ (NSMutableArray *)alertsArray
{
    static NSMutableArray *mArray;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mArray = [NSMutableArray array];
    });
    return mArray;
}

+ (void)alertArrayAddAlert:(LXAlertView *)view
{
    NSMutableArray *array = [self alertsArray];
    [array addObject:view];
    if (array.firstObject == view) {
        [view show];
    }
}

+ (void)alertArrayRemoveAlert:(LXAlertView *)view
{
    NSMutableArray *array = [self alertsArray];
    [array removeObject:view];
    if (array.count) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            LXAlertView *firstView = array.firstObject;
            [firstView show];
        });
    }
}

+ (void)alertWithTitle:(nullable NSString *)title message:(nullable NSString *)message dismissBlock:(nullable void (^)(NSInteger cancelIndex, NSInteger clickIndex))dismissBlock cancelTitle:(nullable NSString *)cTitle otherButtonTitles:(nullable NSArray *)oTitles
{
    LXAlertView *alert = [[LXAlertView alloc] initWithTitle:title message:message dismissBlock:dismissBlock cancelTitle:cTitle otherButtonTitles:oTitles];
    [LXAlertView alertArrayAddAlert:alert];
}

- (instancetype)initWithTitle:(nullable NSString *)title message:(nullable NSString *)message dismissBlock:(nullable void (^)(NSInteger cancelIndex, NSInteger clickIndex))dismissBlock cancelTitle:(nullable NSString *)cTitle otherButtonTitles:(nullable NSArray *)oTitles
{
    if (self = [super init]) {
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        self.dismissBlock = dismissBlock;
        
        self.titleLabel.text = title;
        self.messageLabel.text = message;
        [self.cancelButton setTitle:cTitle forState:UIControlStateNormal];
        
        self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
        self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
        self.firstLine.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-53-[_contentView]-53-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_contentView)]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-17-[_titleLabel]-17-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_titleLabel, _messageLabel)]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-21-[_titleLabel]-8-[_messageLabel]" options:NSLayoutFormatAlignAllLeft | NSLayoutFormatAlignAllRight metrics:nil views:NSDictionaryOfVariableBindings(_titleLabel, _messageLabel)]];
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_firstLine]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_firstLine)]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_messageLabel]-21-[_firstLine(0.5)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_firstLine, _messageLabel)]];
        
        if (oTitles) {
            UIView *lastView = self.firstLine;
            for (int i = 0; i < oTitles.count; i++) {
                UIView *line = [[UIView alloc] init];
                line.backgroundColor = [UIColor colorWithRed:219/255.0 green:219/255.0 blue:223/255.0 alpha:1];
                [self.contentView addSubview:line];
                line.translatesAutoresizingMaskIntoConstraints = NO;
                
                UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
                button.backgroundColor = [UIColor clearColor];
                button.tag = 1 + i;
                [button setTitleColor:self.blueColor forState:UIControlStateNormal];
                [button addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
                [self.contentView addSubview:button];
                [button setTitle:[oTitles objectAtIndex:i] forState:UIControlStateNormal];
                button.translatesAutoresizingMaskIntoConstraints = NO;
                
                if (i == 0 && oTitles.count == 1) {
                    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_cancelButton(button)][line(0.5)][button(_cancelButton)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line, _cancelButton, button)]];
                    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_firstLine][_cancelButton(button)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line, _cancelButton, button)]];
                    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_firstLine][line]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line, _cancelButton, button)]];
                }
                else {
                    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button(line)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line, button)]];
                    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastView][button(44)][line(0.5)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(line, lastView, button)]];
                    
                    if (i == oTitles.count - 1) {
                        lastView = line;
                        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_cancelButton]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_cancelButton)]];
                        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastView][_cancelButton(44)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lastView, _cancelButton)]];
                    }
                }
                
                lastView = line;
            }
        }
        else {
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_cancelButton]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_cancelButton)]];
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_firstLine][_cancelButton(44)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_firstLine, _cancelButton)]];
        }
    }
    return self;
}

- (NSLayoutConstraint *)constraintWithAttribute:(NSLayoutAttribute)attribute onView:(UIView *)view constant:(CGFloat)constant
{
    for (NSLayoutConstraint *constaraint in view.constraints) {
        if (constaraint.firstAttribute == attribute && constaraint.constant == constant) {
            return constaraint;
        }
    }
    return nil;
}

#pragma mark - Animations
- (void)show
{
    [UIView animateWithDuration:0.3 animations:^{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
    } completion:^(BOOL finished) {
        
    }];

    self.contentView.transform = CGAffineTransformMakeScale(1.03, 1.03);
    [UIView animateWithDuration:0.2 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.contentView.transform = CGAffineTransformMakeScale(1, 1);
        
    } completion:^(BOOL finished) {
        
    }];;
}

- (void)dismiss:(UIButton *)btn
{
    __weak typeof(self) wSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        [self removeFromSuperview];
    } completion:^(BOOL finished) {
        if (wSelf.dismissBlock) {
            wSelf.dismissBlock(0, btn.tag);
        }
        
        [LXAlertView alertArrayRemoveAlert:self];
    }];
}

#pragma mark - Property Methods
- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectZero];
        _contentView.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
        _contentView.center = self.center;
        _contentView.clipsToBounds = YES;
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.cornerRadius = 10.0f;
        [self addSubview:_contentView];
    }
    return _contentView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.backgroundColor = [UIColor clearColor];
        label.numberOfLines = 0;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:20];
        label.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:label];
        _titleLabel = label;
    }
    return _titleLabel;
}

- (UILabel *)messageLabel
{
    if (!_messageLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.backgroundColor = [UIColor clearColor];
        label.numberOfLines = 0;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:16];
        label.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:label];
        _messageLabel = label;
    }
    return _messageLabel;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
        button.backgroundColor = [UIColor clearColor];
        button.tag = 0;
        [button setTitleColor:self.blueColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
        _cancelButton = button;
    }
    return _cancelButton;
}

- (UIView *)firstLine
{
    if (!_firstLine) {
        _firstLine = [[UIView alloc] initWithFrame:CGRectZero];
        _firstLine.backgroundColor = [UIColor colorWithRed:219/255.0 green:219/255.0 blue:223/255.0 alpha:1];
        [self.contentView addSubview:_firstLine];
    }
    return _firstLine;
}

- (UIColor *)blueColor
{
    return [UIColor colorWithRed:0 green:122/255.0 blue:1 alpha:1];
}

@end
